<?php

/**
 * Radcodes - SocialEngine Module
 *
 * @category   Application_Extensions
 * @package    Game
 * @copyright  Copyright (c) 2009-2010 Radcodes LLC (http://www.radcodes.com)
 * @license    http://www.radcodes.com/license/
 * @version    $Id$
 * @author     Vincent Van <vincent@radcodes.com>
 */
 
 
class Game_AdminDistributorsController extends Core_Controller_Action_Admin
{
  
  public function init()
  {
    if (!Engine_Api::_()->game()->checkLicense()) {
      return $this->_redirectCustom(array('route'=>'admin_default', 'module'=>'game', 'controller'=>'settings'));
    }
        
    if( !Engine_Api::_()->core()->hasSubject() )
    {
      if( ($type = $this->_getParam('type')) &&
          null !== ($distributor = Engine_Api::_()->getItemTable('game_distributor')->getDistributor($type)) )
      {
        Engine_Api::_()->core()->setSubject($distributor);
      }
    }

    $this->_helper->requireSubject->setActionRequireTypes(array(
      'delete' => 'game_distributor',
    ));
    
    
  }
  
  protected function loadNagivation()
  {
    $this->view->navigation = $navigation = Engine_Api::_()->getApi('menus', 'core')
      ->getNavigation('game_admin_main', array(), 'game_admin_main_distributors');
  }
  
  public function indexAction()
  {
    $this->loadNagivation();

    $this->view->distributors = Engine_Api::_()->getItemTable('game_distributor')->fetchAll();
  }

  public function editAction()
  {
    $this->loadNagivation();
    
    $this->view->distributor = $distributor = Engine_Api::_()->core()->getSubject('game_distributor');
    
    $this->view->form = $form = $distributor->getForm('setting');
    
    if (!$this->getRequest()->isPost())
    {
      $form->populate($distributor->config);
      return;
    }
    
    if (!$form->isValid($this->getRequest()->getPost()))
    {
      return; 
    }
    
    $db = Engine_Db_Table::getDefaultAdapter();
    $db->beginTransaction();

    try
    {
      
      $values = $form->getValues();
      $distributor->config = $values;
      $distributor->save();
      
      $db->commit();
      
      $savedChangesNotice = Zend_Registry::get('Zend_Translate')->_("Your changes were saved.");
      $form->addNotice($savedChangesNotice);
    }

    catch( Exception $e )
    {
      $db->rollBack();
      throw $e;
    }
  }
  
  public function importAction()
  {
    set_time_limit(0);
    
    $this->loadNagivation();
    $viewer = Engine_Api::_()->game()->getDefaultOwner();    

    $this->view->distributor = $distributor = Engine_Api::_()->core()->getSubject('game_distributor');

    $this->view->form = $form = $distributor->getForm('import');
        

    if (!$this->getRequest()->isPost())
    {
      $form->type_id->setValue($distributor->type);
      return;
    }

    if (!$form->isValid($this->getRequest()->getPost()))
    {
      return; 
    }
 

    $formValues = $values = $form->getValues();
    
    $config = array_merge($distributor->config, $values);
    $plugin = $distributor->getPlugin();
    $plugin->loadConfig($config);

    $this->view->plugin = $plugin;

    try
    {
      $data = $plugin->fetchGames();
    }
    catch (Zend_Http_Client_Adapter_Exception $ex)
    {
      $this->view->exception = $ex;
      return;
    }
        
    $games = array();
    
    if (count($data))
    {
      
      ob_clean();
      while (ob_get_level() > 0) {
        ob_end_flush();
      }
      ob_start();
      
      echo '<div id="game_import_live_log" style="font-family: Arial; font-size: 11px; padding: 10px;">Fetching games ...';      
      
      $table = Engine_Api::_()->getItemTable('game');
      $db = $table->getAdapter();

      
      $categoryMapping = Engine_Api::_()->getApi('settings', 'core')->game_categorymapping;

      $emptyString = str_repeat(" ", 512);
      foreach ($data as $k => $values)
      {
        //sleep(2);
        $params = array('distributor_type' => $distributor->type, 'distributor_ref_id' => $values['distributor_ref_id']);
        $existing = Engine_Api::_()->getItemTable('game')->countGames($params);
        echo ($k+1)." ... ".$emptyString;                                                                                                  
        ob_flush();flush();
        if (!$existing)
        {
          $values['distributor_type'] = $distributor->type;
          
          $values = Engine_Api::_()->game()->importGame($values, $formValues);  
        }
        else
        {
          $values['import_result'] = 'already exist';
        }
        
        $data[$k] = $values;
      }
      
      echo "Finish!</div>";
      ob_flush();flush();
      
      
    }

    $this->view->games = $data;
  }
  // import
  
  public function fetchCsvAction()
  {
    $this->loadNagivation();

    $this->view->form = $form = new Game_Form_Admin_Distributor_Fetch();
    
    if (!$this->getRequest()->isPost())
    {
      return;
    }

    if (!$form->isValid($this->getRequest()->getPost()))
    {
      return; 
    }
 
    $formValues = $form->getValues();

    $filename = $formValues['filename'];
    $file = APPLICATION_PATH_TMP . DS . $filename;
    
    $row = 1;
    if (($handle = fopen($file, "r")) !== FALSE)
    {
      
      ob_clean();
      while (ob_get_level() > 0) {
        ob_end_flush();
      }
      ob_start();

      $csvCategories = Game_Model_Category::getCsvCategories();
      
      $range = $form->getDataBound($filename);
      //print_r($range);
      
      $table = Engine_Api::_()->getItemTable('game');
      $imported_id = $table->getMaxImportId($range);      
      
      echo '<div id="game_import_live_log" style="font-family: Arial; font-size: 11px; padding: 10px; white-space: pre-wrap; overflow-y: scroll; width: 900px; margin: 0 auto; text-align: center;">Fetching games from ';
      echo "\"$filename\": min_import_id={$range['min']} max_import_id={$range['max']} current_imported_id={$imported_id}";      
      
      $headers = array();
      $emptyString = str_repeat("&nbsp;", 50);
      $nlString = "\n";
      while (($data = fgetcsv($handle, 10000, ",")) !== false)
      {
        if (empty($headers)) {
          $headers = $data;
          echo $nlString . "Loaded headers";
          continue;
        }
        
        if (count($data) != count($headers)) {
          echo $nlString . "Data count not match | Skip";
          continue;
        }
        
        $values = array();
        foreach ($headers as $k => $v) {
          $values[$v] = $data[$k];
        }
        
        $values['distributor_type'] = 'mochi';
        $values['status'] = $formValues['status'];
        
        echo $nlString . ($values['import_id']).": ";     
        
        if ($formValues['querycheck']) {
          $existing = Engine_Api::_()->getItemTable('game')->countGames(array('distributor_type' => 'mochi', 'distributor_ref_id' => $values['distributor_ref_id']));
          echo 'live';
        }
        else {
          $existing = ($values['import_id'] <= $imported_id);
        }
        
        if ($existing) {
          echo " FOUND | SKIP import id";
        }
        else {

          $values['categories'] = array($csvCategories[$values['category_id']]);
          
          $values = Engine_Api::_()->game()->importGame($values, $formValues);  

          if (is_int($values['import_result']) && $values['import_result'] == $values['game_id']) {
            echo " IMPORTED | game_id = ".$values['game_id'];
          }
          else {
            echo " ".$values['import_result'];
          }
          
          //print_r($values);
        }
        
        echo $emptyString;
        ob_flush();flush();
        
        /*
        if ($i++ <= 10) {
          print_r($values);
          break;
        }
        */
      }

      fclose($handle);
      
      echo $nlString."Finish!</div>";
      ob_flush();flush();      

      $savedChangesNotice = Zend_Registry::get('Zend_Translate')->_("Game Pack Loaded Successfully!");
      $form->addNotice($savedChangesNotice);      
      
    }
    else {
      $savedChangesNotice = Zend_Registry::get('Zend_Translate')->_("Game Pack Failed To Load!");
      $form->addError($savedChangesNotice);   
    }
  }
  
  public function testAction()
  {
    // Disable view and layout rendering
    $this->_helper->viewRenderer->setNoRender();
    $this->_helper->layout()->disableLayout();
    
  	$this->loadNagivation();
  	$frontController = Zend_Controller_Front::getInstance();
	$frontController->setParam('disableOutputBuffering', 1);
	ob_clean();
    while (ob_get_level() > 0) {
      ob_end_flush();
    }
    ob_start();

		for ($i=0; $i <= 20; $i++) {

			sleep(2);
			echo "<br>";
			echo $i;
			echo '<br>Some versions of Microsoft Internet Explorer will only start to display the page after they have received 256 bytes of output, so you may need to send extra whitespace before flushing to get those browsers to display the page. Some versions of Microsoft Internet Explorer will only start to display the page after they have received 256 bytes of output, so you may need to send extra whitespace before flushing to get those browsers to display the page. Some versions of Microsoft Internet Explorer will only start to display the page after they have received 256 bytes of output, so you may need to send extra whitespace before flushing to get those browsers to display the page. Some versions of Microsoft Internet Explorer will only start to display the page after they have received 256 bytes of output, so you may need to send extra whitespace before flushing to get those browsers to display the page. ';
			
			ob_flush();flush();
		}

  }
}